import React, {Component} from "react";
import {Modal, Toast} from "antd-mobile";
import {restApiRequest} from "../Public/Api/Public";
import Login from "../Public/Components/Login";

const alert = Modal.alert;

export default class Setting extends Component {

  constructor(props, context) {
    super(props, context);
    this.state = {
      sessionkey: localStorage.getItem('sessionkey'),
      userInfo: '',
      nickname: '',
      head_image_url: '',
      sex: '',
      school_name: '',
      cell_number: '',
      visible: false,
    }
  };

  componentWillMount() {
    //判断是否登录
    console.log('setting' + this.state.sessionkey);
    if (this.state.sessionkey === null) {
      this.setState({
        visible: true
      })
    } else {
      let param = {sessionkey: this.state.sessionkey};
      let jsonData = restApiRequest.getSign(param);
      this.fetchData(jsonData, 'init');
    }
  }

  //获取用户信息
  fetchData(jsonData, type) {
    let url = '/shop/api/getUserInfo';
    restApiRequest.fetchp(url, jsonData).then((response) => {
      if (!response.ok) {
        let error = new Error(response.statusText);
        error.response = response;
        throw error;
      } else {
        return response.json();
      }
    }).then((response_json) => {
      console.log(response_json);
      //渲染用户信息
      let res_code = response_json.code;
      if (res_code === '0000') {
        let responseData = response_json.data;
        this.setState({
          userInfo: responseData,
          head_image_url: responseData.head_image_url,
          nickname: responseData.nickname,
          sex: responseData.sex,
          school_name: responseData.school_name,
          cell_number: responseData.cell_number,
        })
      } else if (res_code === '8888') {
        this.setState({
          nickname: '小地主',
          visible: true,
        });
      }
    }).catch((ex) => {
      console.log(ex);
    });
  }

  //修改用户信息
  updateUserInfo(paramer) {
    let edit_url = '/shop/api/editUserInfo';
    // let paramer = {nickname:this.state.nickname, sessionkey: sessionkey};
    let jsonData = restApiRequest.getSign(paramer);
    restApiRequest.fetchp(edit_url, jsonData).then((response) => {
      if (!response.ok) {
        let error = new Error(response.statusText);
        error.response = response;
        throw error;
      } else {
        return response.json();
      }
    }).then((response_json) => {
      // console.log(response_json);
      let res_code = response_json.code;
      if (res_code === '0000') {
        console.log(response_json);

      }
    }).catch((ex) => {
      console.log(ex);
    });

  }


  changeHead() {
    alert('提醒', '头像请前往APP下修改', [
      { text: '确定', onPress: () => console.log('cancel'), style: 'default' },
    ]);
  }

  changeNickname() {
    Modal.prompt('修改昵称', '', [
      {text: '取消修改'},
      {
        text: '确认修改', onPress: value => {
        value == '' ? Toast.info('昵称不能为空', 1) :
          [this.setState({nickname: value}), (this.updateUserInfo({
            nickname: value,
            sessionkey: this.state.sessionkey
          }))]
      }
      },
    ], 'plain-text', '')
  }

  changeSex() {
    Modal.alert('修改性别', <div>请选择性别</div>, [
      {
        text: '帅哥',
        onPress: () => [this.setState({sex: 1}), this.updateUserInfo({sex: 1, sessionkey: this.state.sessionkey})]
      },
      {
        text: '美女',
        onPress: () => [this.setState({sex: 2}), this.updateUserInfo({sex: 2, sessionkey: this.state.sessionkey})]
      },
      {text: '先不改了', onPress: () => console.log('第3个按钮被点击了')},
    ])
  }

  changeSchool() {
    Modal.prompt('修改学校信息', '', [
      {text: '取消修改'},
      {
        text: '确认修改', onPress: value => {
        value == '' ? Toast.info('学校信息不能为空', 1.5) :
          [this.setState({school_name: value}), this.updateUserInfo({
            school_name: value,
            sessionkey: this.state.sessionkey
          })]
      }
      },
    ], 'plain-text', '')
  }

  //切换账号成功回调
  onLoginCallback(){
    this.setState({
      visible:false,
      cell_number:localStorage.getItem('cell_number').replace(/(\d{3})(\d{4})(\d{4})/, "$1 $2 $3"),
    });
    let param = {sessionkey:localStorage.getItem('sessionkey')};
    let jsonData = restApiRequest.getSign(param);
    this.fetchData(jsonData, 'init');

  }

  changePhone() {
    alert('提醒', '是否更换当前手机号', [
      { text: '取消', onPress: () =>console.log('取消'), style: 'default' },
      { text: '确定', onPress: () =>this.setState({visible:true}), style: 'default' },
    ]);
  }

  //退出登录，清除缓存
  async jumpLoginOut() {
    try {
      await localStorage.removeItem('sessionkey');
      await localStorage.removeItem('cell_number');
      await localStorage.removeItem('user_id');
        this.props.history.push({
        pathname: '/UserIndex',
      })

    } catch (error) {
      console.log(error.message);
    }
  }


  render() {
    return (
      <div>
        {this.state.visible ?<Login onClosedCallback={() => {this.setState({visible: false})}} onLoginCallback={()=>this.onLoginCallback()}/>:null}
        <div className="setting-list">

          <section className="setting-item" onClick={()=>this.changeHead()}>
            <span>修改头像</span>
            <img className="setting-list-img" src={this.state.head_image_url}/>
          </section>

          <div className="setting-line"/>

          <section className="setting-item" onClick={() => this.changeNickname()}>
            <span>昵称</span>
            <span>{this.state.nickname}</span>
          </section>

          <div className="setting-line"/>

          <section className="setting-item" onClick={()=>this.changeSex()}>
            <span>性别</span>
            <span>{this.state.sex == 1 ? '男' : '女'}</span>
          </section>

          <div className="setting-line"/>

          <section className="setting-item" onClick={() => this.changeSchool()}>
            <span>所在学校</span>
            <span>{this.state.school_name}</span>
          </section>

          <section className="setting-item setting-item-placeholder" onClick={() => this.changePhone()}>
            <span>绑定手机</span>
            <span>{this.state.cell_number.replace(/(\d{3})(\d{4})(\d{4})/, "$1 $2 $3")}</span>
          </section>

        </div>

        <section className="setting-btn-wrap">
          <button
            type="button"
            onTouchStart={()=>this.jumpLoginOut()}
            className="setting-btn"
          >退出登录</button>

        </section>

      </div>
    )
  }
}
